package com.ruiyi.adrobot.service.device.impl;

import com.ruiyi.adrobot.beans.Device;
import com.ruiyi.adrobot.beans.Robot;
import com.ruiyi.adrobot.beans.VirtualDevice;
import com.ruiyi.adrobot.mongo.device.DeviceRepository;
import com.ruiyi.adrobot.service.device.DeviceService;
import com.ruiyi.adrobot.utils.DateUtil;
import com.ruiyi.adrobot.utils.IMEIUtil;
import com.ruiyi.adrobot.utils.LoggerUtil;
import com.ruiyi.adrobot.utils.RandomUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * Created by Lenovo on 2017/5/8.
 */
@Service
public class DeviceServiceImpl implements DeviceService {
    @Autowired
    private DeviceRepository deviceRepository;

    @Override
    public void resolveTxt() {
        try {
            String encoding = "GBK";
            File file = new File("E:/公司资料/device.txt");
            if (file.isFile() && file.exists()) { //判断文件是否存在
                InputStreamReader read = new InputStreamReader(
                        new FileInputStream(file), encoding);//考虑到编码格式
                BufferedReader bufferedReader = new BufferedReader(read);
                String lineTxt;
                Map<String, String> map = new LinkedHashMap<>();
                Device device = new Device();
                while ((lineTxt = bufferedReader.readLine()) != null) {
                    try { // 补货主键重复，及设备型号中包含字母的异常
                        String[] deviceArr = lineTxt.split("&");
                        for (String str : deviceArr) {
                            map.put(str.split("=")[0], str.split("=")[1]);
                        }
                        // imei不足15位
                        if (map.get("uuid").length() != 15) {
                            continue;
                        }
                        device.setImei(map.get("uuid"));
                        device.setBrand(map.get("device_brand").replace("+", " ").replace("%", " "));
                        device.setModel(map.get("device_type").replace("+", " ").replace("%", " "));
                        device.setVersionAndroid(map.get("os_version"));
                        device.setCreateDate(DateUtil.getCurrentTime());
                        device.setOsApi(Integer.valueOf(map.get("os_api")));
                        device.setOpenId(map.get("openudid"));
                        device.setResolution(map.get("resolution"));
                        device.setDpi(Integer.valueOf(map.get("dpi")));
                        deviceRepository.insert(device);
                    } catch (Exception e) {
                        continue;
                    }
                }
                read.close();
                LoggerUtil.info("构建完成");
            } else {
                System.out.println("找不到指定的文件");
            }
        } catch (Exception e) {
            System.out.println("读取文件内容出错");
            e.printStackTrace();
        }
    }

    @Override
    public void buildModels() {
        deviceRepository.buildModels();
    }

    @Override
    public void buildBaseDevices_v1() {
        List<Device> oldDevices = deviceRepository.findAll();
        for (Device device : oldDevices) {
            Device newDevice = new Device();
            try {
                newDevice.setImei(IMEIUtil.buildIMEIBy8(device.getImei().substring(0, 8)));
            } catch (Exception e) {
                continue;
            }
            newDevice.setOpenId(UUID.randomUUID().toString().replace("-", "").substring(0, 16));
            newDevice.setResolution(device.getResolution());
            newDevice.setDpi(device.getDpi());
            newDevice.setCreateDate(DateUtil.getCurrentTime());
            newDevice.setModel(device.getModel());
            newDevice.setBoard(device.getBoard());
            newDevice.setDisplayId(device.getDisplayId());
            newDevice.setVersionAndroid(device.getVersionAndroid());
            newDevice.setBrand(device.getBrand());
            newDevice.setOsApi(device.getOsApi());
            Device oldDevice = deviceRepository.findByImei(newDevice.getImei());
            if (null == oldDevice) {
                deviceRepository.save(newDevice);
            }
        }
    }

    @Override
    public void buildVirtualDevice() {
        List<Device> realDevices = deviceRepository.findAll();
        int i = 0;
        for (Device device : realDevices) {
            LoggerUtil.info("构建第" + i++ + "个");
            deviceRepository.insertVirtualDevice(device);
        }
    }

    /**
     * 查找满足条件的一个随机设备信息
     */
    @Override
    public Device randomDeviceByModelAndVirtualAndAccountInfosFunAndImeiNotInAndAccountInfosCreateDateBetween(String model, boolean virtual, Integer fun, List<String> usedImeis, String startDate, String endDate) {
        Device device;
        if (virtual) {
            device = deviceRepository.findRandomDeviceByModelAndUsedFunsNot(model, null);
            VirtualDevice virtualDevice = deviceRepository.findRandomDeviceByAccountInfosFunAndAccountInfosCreateDateBetween(fun, startDate, endDate, device.getImei().substring(0, 8));
            virtualDevice2Device(device, virtualDevice);
        } else {
            device = deviceRepository.findRandomDeviceByModelAndAccountInfosFunAndAccountInfosCreateDateBetween(model, fun, startDate, endDate);
        }
        return device;
    }

    private void virtualDevice2Device(Device device, VirtualDevice virtualDevice) {
        device.setImei(virtualDevice.getImei());
        device.setUsedFuns(virtualDevice.getUsedFuns());
        device.setProvinceId(virtualDevice.getProvinceId());
        device.setCityId(virtualDevice.getCityId());
    }

    @Override
    public Device findDeviceByImei(String imei, boolean virtual) {
        Device device;
        if (virtual) {
            device = deviceRepository.findRegexImei(imei.substring(0, 8));
            VirtualDevice virtualDevice = deviceRepository.findVirtualDeviceByImei(imei);
            virtualDevice2Device(device, virtualDevice);
        } else {
            device = deviceRepository.findOne(imei);
        }
        return device;
    }

    @Override
    public Device findRandomNotUsedDevice(Integer fun, boolean virtual, List<Robot> canExcuteRobots) {
        Device device = null;
        for (Robot robot : canExcuteRobots) {
            LoggerUtil.info("根据设备型号查找：" + robot.getModel());
            if (virtual) {
                device = deviceRepository.findRandomDeviceByModelAndUsedFunsNot(robot.getModel(), null);
                if (null == device) {
                    LoggerUtil.info("真实设备库中无该设备型号：" + robot.getModel());
                    continue;
                }
                VirtualDevice virtualDevice = deviceRepository.findRandomNotUsedVirtualDevice(fun, device.getImei().substring(0, 8));
                if (null != virtualDevice) {
                    virtualDevice2Device(device, virtualDevice);
                } else {
                    device = null;
                }
            } else {
                List<Device> devices = deviceRepository.findDevicesByModelAndUsedFunsNot(robot.getModel(), fun);
                LoggerUtil.info("可用设备总数" + devices.size());
                if (devices.size() > 0) {
                    device = devices.get(RandomUtil.nextInt(devices.size()));
                    LoggerUtil.info("使用IMEI:" + device.getImei());
                }
            }
            if (null != device) {
                device.setExcuteSimCode(robot.getSimCode());
                break;
            }
        }
        if (null == device) {
            // 若未找到，则不按型号查找
            if (virtual) {
                VirtualDevice virtualDevice;
                int count = 0;
                do {
                    count++;
                    LoggerUtil.info("循环随机查找设备型号次数：" + count);
                    device = deviceRepository.findRandomModel();
                    virtualDevice = deviceRepository.findRandomNotUsedVirtualDevice(fun, device.getImei().substring(0, 8));
                } while (null == virtualDevice);
                virtualDevice2Device(device, virtualDevice);
                device.setExcuteSimCode(canExcuteRobots.get(0).getSimCode());
            } else {
                List<Device> devices = deviceRepository.findDevicesByUsedFunsNot(fun);
                if (devices.size() > 0) {
                    device = devices.get(RandomUtil.nextInt(devices.size()));
                    device.setExcuteSimCode(canExcuteRobots.get(0).getSimCode());
                }
            }
            if (null != device) {
                LoggerUtil.info("未按型号查找到的设备信息：" + device.getModel());
            }
        }
        return device;
    }

    @Override
    public Device findOne(String imei) {
        return deviceRepository.findOne(imei);
    }

    @Override
    public VirtualDevice findVirtualDeviceByImei(String imei) {
        return deviceRepository.findVirtualDeviceByImei(imei);
    }

    @Override
    public void saveOrUpdateVirtualDeviceAccounts(VirtualDevice virtualDevice) {
        deviceRepository.saveOrUpdateVirtualDeviceAccounts(virtualDevice);
    }

    @Override
    public void removeUsedFunsById(String imei, Integer fun, Boolean virtual) {
        deviceRepository.removeUsedFunsById(imei, fun, virtual);
    }

    @Override
    public List<Device> findAll() {
        return deviceRepository.findAll();
    }

    @Override
    public Device findByImei(String imei) {
        return deviceRepository.findByImei(imei);
    }

    @Override
    public void saveOrUpdate(Device device) {
        deviceRepository.save(device);
    }

    public static void main(String[] args) {
        for (int i = 0; i < 20; i++) {
            System.out.println(UUID.randomUUID().toString().replace("-", "").substring(0, 16));
        }
    }
}
